# -*- coding: utf-8 -*-
import sys
if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')
import urllib2, urllib, re, time, datetime, random, os
from pprint import pprint
from traceback import print_exc
from urllib import quote_plus, unquote, quote, urlencode, unquote_plus
#import httplib

#dbg = True
#dbglevel = 3
#httplib.HTTPConnection.debuglevel = 1

#def log(description, level=0):
#    if dbg and dbglevel > level:
#        try:
#            print description
#        except UnicodeEncodeError:
#            print description.encode('utf-8')

TAG_RE = re.compile(r'<[^>]+>')
SPACE_RE = re.compile(r'\s+')

def remove_tags(text):
    return SPACE_RE.sub(' ', TAG_RE.sub('', text.replace('<br/>', '{br/}')).strip()).replace('{br/}', "\n")

def re_search_result(rep, text, group):
    match = rep.search(text)
    if match:
        return match.group(group)

def re_match_result(rep, text, group):
    match = rep.match(text)
    if match:
        return match.group(group)

def get_js_value(text, name, sep = '=', matchWholeLine=False):
    prefix = r'^\s*' if matchWholeLine else ''
    suffix = r'\s*$' if matchWholeLine else ''
    match = re.search(prefix + name.replace('.', r'\.') + r'\s*'+sep+'\s*("([^"]*)"\s*;?|([^"\s].*?)\s*[;}])' + suffix, text, re.M)
    if match:
        ret = match.group(2) or match.group(3)
        log("get_js_value [%s] = [%s]" % (name, ret))
        return ret
#    match = re.search(prefix + name.replace('.', r'\.') + r'\s*'+sep+'\s*([^"\s].*?)\s*[;}]' + suffix, text, re.M)
#    if match:
#        log("get_js_value [%s] = [%s]" % (name, match.group(1)))
#        return match.group(1)
    return None

def get_js_response_content(text):
    return re_search_result(re.compile(r'^\s*[^(]*\(([\s\S]*?)\);?\s*$'), text, 1)

def get_str_duration(secs):
    if secs < 60:
        return '0:%02d' % secs
    if secs < 3600:
        return '%d:%02d' % (secs / 60, secs % 60)
    return '%d:%02d:%02d' % (secs / 3600, (secs % 3600) / 60, secs % 60)

def sizeof_fmt(num):
    num = int(num)
    for x in ['bytes','KB','MB','GB']:
        if num < 1024.0 and num > -1024.0:
            return "%3.2f%s" % (num, x)
        num /= 1024.0
    return "%3.2f%s" % (num, 'TB')

# Plugin constants
UserAgent_IPAD = 'Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; ja-jp) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5'
UserAgent_IE = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
UserAgent_Chrome = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'


def get_timestamp_long():
    return str(long(time.time()*1000))

def get_random_short():
    return int(random.random() * 10000000)

def addURLOptions(url, **args):
    tmp = url.split('|')
    if len(tmp) == 2:
        url, opts = tmp
        opts = opts.split('&')
        opts = dict(opt.split('=', 2) for opt in opts)
        opts = dict([unquote_plus(key), unquote_plus(val)] for key, val in opts.iteritems())
#        pprint(opts)
    else:
        opts = {}
    opts.setdefault('User-Agent', UserAgent_IE)
    opts.update(args)
#    pprint(opts)
    return '%s|%s' % (url, urlencode(opts))

def RequestFromURLWithOption(url):
    tmp = url.split('|')
    if len(tmp) == 2:
        url, opts = tmp
        opts = opts.split('&')
        opts = dict(opt.split('=', 2) for opt in opts)
        opts = dict([unquote_plus(key), unquote_plus(val)] for key, val in opts.iteritems())
#        pprint(opts)
    else:
        opts = {}
    req = urllib2.Request(url)
    for key, val in opts.iteritems():
        req.add_header(key, val)
    return req

